package com.boot_reggie.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot_reggie.Dao.OrderMapper;
import com.boot_reggie.Service.OrderService;
import com.boot_reggie.common.CustomException;
import com.boot_reggie.domain.*;
import com.boot_reggie.filter.BaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private OrdersDetailServiceImpl ordersDetailService;

    @Autowired
    private ShoppingCartServiceImpl shoppingCartService;

    @Autowired
    private AdressServiceImpl adressService;

    @Autowired
    private AlipayServiceImpl alipayService;
    @Override
    @Transactional
    public Long submit(Orders order, HttpSession session, HttpServletRequest req, HttpServletResponse res) throws IOException {
        User user = (User)session.getAttribute("userInfo");
//        获取用户id
        Long userID = user.getId();
//        查询当前用户购物车数据
        LambdaQueryWrapper<ShoppingCart> lwq = new LambdaQueryWrapper<>();
        lwq.eq(ShoppingCart::getUserId,userID);
        List<ShoppingCart> list = shoppingCartService.list(lwq);
        if(list == null || list.size() == 0){
            throw new CustomException("购物车为空");
        }
//        查询地址信息
        LambdaQueryWrapper<AddressBook> lwq1 = new LambdaQueryWrapper<>();
        lwq1.eq(AddressBook::getUserId,userID);
        lwq1.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = adressService.getOne(lwq1);
        if(addressBook == null){
            throw new CustomException("地址为空");
        };
        AtomicInteger atomicInteger = new AtomicInteger(0);
        Long orderId = IdWorker.getId();
        /*计算金额并封装订单详细*/
        List<OrderDetail> orderDetailList = list.stream().map(item->{
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setAmount(item.getAmount());
            atomicInteger.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;

        }).collect(Collectors.toList());
        /*向订单表插入一条数据*/

        Orders orders = new Orders();
        //订单号
        orders.setNumber(String.valueOf(orderId));
//        2待派送
        orders.setStatus(0);
        /*userId*/
        orders.setUserId(userID);
        /*地址id*/
        orders.setAddressBookId(addressBook.getId());
        /*创建时间*/
        orders.setCheckoutTime(LocalDateTime.now());
        /*结账时间*/
        orders.setOrderTime(LocalDateTime.now());
        /*支付方式*/
        orders.setPayMethod(1);
        /*备注*/
        orders.setRemark(order.getRemark());
        /*用户名*/
        orders.setUserName(user.getName());
        /*收货人*/
        orders.setConsignee(addressBook.getConsignee());
        /*手机号*/
        orders.setPhone(addressBook.getPhone());
        /*地址*/
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        /*金额*/
        orders.setAmount(new BigDecimal(atomicInteger.get()));
        /*插入一条数据*/
        this.save(orders);
        /*向订单详细插入多条数据*/
        ordersDetailService.saveBatch(orderDetailList);
        /*清空购车数据*/
        shoppingCartService.remove(lwq);

        return orderId;
    }

    @Override
    public List<OrdersDto> getOrders(User user) {
        /*根据user查询最近的一次订单*/
        LambdaQueryWrapper<Orders> lwq = new LambdaQueryWrapper<>();
        lwq.eq(Orders::getUserId,user.getId());
        lwq.eq(Orders::getComment,1);
        lwq.orderByDesc(Orders::getOrderTime);
        List<OrdersDto> dtoList = new ArrayList<>();
        List<Orders> list =  this.list(lwq);
        for (Orders orders : list) {
            OrdersDto ordersDto = new OrdersDto();
            ordersDto.setAddress(orders.getAddress());
            ordersDto.setAmount(orders.getAmount());
            ordersDto.setConsignee(orders.getConsignee());
            ordersDto.setAddressBookId(orders.getAddressBookId());
            ordersDto.setCheckoutTime(orders.getCheckoutTime());
            ordersDto.setId(orders.getId());
            ordersDto.setPayMethod(orders.getPayMethod());
            ordersDto.setNumber(orders.getNumber());
            ordersDto.setPhone(orders.getPhone());
            ordersDto.setStatus(orders.getStatus());
            dtoList.add(ordersDto);
        };

        for (OrdersDto ordersDto : dtoList) {
            ordersDto.getNumber();
            LambdaQueryWrapper<OrderDetail> lwq1 = new LambdaQueryWrapper<>();
            lwq1.eq(OrderDetail::getOrderId,ordersDto.getNumber());
            List<OrderDetail> list1  = ordersDetailService.list(lwq1);
            System.out.println(list1);
            ordersDto.setList(list1);
        }
        System.out.println(dtoList);
//        OrdersDto ordersDto = new OrdersDto();
//        BeanUtils.copyProperties(orders,ordersDto);
        return dtoList;
    }

    @Override
    public IPage<Orders> getAll(int page ,int size) {
        IPage page1 = new Page(page,size);
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper();
        System.out.println("用户id"+BaseContext.getThreadLocal1());
        lambdaQueryWrapper.eq(Orders::getUserId, BaseContext.getThreadLocal1());
        lambdaQueryWrapper.eq(Orders::getComment,1);
        lambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        page1 = this.page(page1,lambdaQueryWrapper);
        return page1;
    }

    @Override
    public OrdersDto getShop(Long id) {
        LambdaQueryWrapper<Orders> lwq = new LambdaQueryWrapper<>();
        lwq.eq(Orders::getNumber,id);
        Orders orders = this.getOne(lwq);
        LambdaQueryWrapper<OrderDetail> lwq1 = new LambdaQueryWrapper<>();
        lwq1.eq(OrderDetail::getOrderId,orders.getNumber());
        List<OrderDetail> list = ordersDetailService.list(lwq1);
        OrdersDto ordersDto = new OrdersDto();
        ordersDto.setAddress(orders.getAddress());
        ordersDto.setAmount(orders.getAmount());
        ordersDto.setConsignee(orders.getConsignee());
        ordersDto.setAddressBookId(orders.getAddressBookId());
        ordersDto.setCheckoutTime(orders.getCheckoutTime());
        ordersDto.setId(orders.getId());
        ordersDto.setPayMethod(orders.getPayMethod());
        ordersDto.setNumber(orders.getNumber());
        ordersDto.setPhone(orders.getPhone());
        ordersDto.setStatus(orders.getStatus());
        ordersDto.setRemark(orders.getRemark());
        ordersDto.setComment(orders.getComment());
        ordersDto.setList(list);
        return ordersDto;
    }

    @Override
    public IPage<Orders> getOrders(String order, String time1, String time2,int page,int size) {
        LambdaQueryWrapper<Orders> lwq = new LambdaQueryWrapper<>();
        lwq.like(!order.isEmpty(),Orders::getNumber,order);
        lwq.eq(Orders::getComment,1);
        lwq.orderByDesc(Orders::getOrderTime);
        System.out.println("time1"+time1);
        System.out.println("time2"+time2);
        lwq.orderByDesc(Orders::getOrderTime);
        lwq.between(!time2.isEmpty(),Orders::getOrderTime,time1,time2);
        IPage page1 = new Page(page,size);
        page1 = this.page(page1,lwq);
        System.out.println(page1.getRecords());
        return page1;
    }

    @Override
    public List<Orders> getDingin() {
        LambdaQueryWrapper<Orders> lwq = new LambdaQueryWrapper<>();
        lwq.eq(Orders::getStatus,1);
        List<Orders> list = this.list(lwq);
        return list;
    }

    @Override
    public void updateOrders(String id) {
        LambdaQueryWrapper<Orders> lwq = new LambdaQueryWrapper<>();
        lwq.eq(Orders::getNumber,id);
        Orders orders = this.getOne(lwq);
        orders.setComment(1);
        this.updateById(orders);

    }


}
